import React from 'react';
import {connect} from 'dva';
import {
    Table,
    Row,
    Col,
    Form,
    Input,
    Icon,
    InputNumber,
    Radio,
    DatePicker,
    Select,
    Upload,
    Button,
    message
} from 'antd';

const R = require('ramda');
const dateFormat = 'YYYY-MM-DD';
const {RangePicker} = DatePicker;
import RightContacts from '../../../utils/RightConstants';
import BizParams from '../../../components/commons/BizParams'
import CustomerDetail from '../../../components/customer/components/CustomerDetail';
import OrderDetail from '../../../components/order/components/OrderDetail';
import CstSettlement from '../../../components/cstSettlement/CstSettlement';
import LesseeSettlement from "../../../components/lesseeSettlement/LesseeSettlement";
import RightBox from "../../../components/commons/RightBox";
import Constants from "../../../utils/Constants";
import EditOutbuy from '../../../components/outbuy/components/EditOutbuy';

const FormItem = Form.Item;
const Option = Select.Option;
const RadioGroup = Radio.Group;
export default connect(({customerManage, orderManage, businessAgreement, statement, capital, customerReport, blacklist, customs}) => ({
    customerManage,
    orderManage,
    businessAgreement,
    statement,
    capital,
    customerReport,
    blacklist,
    customs
}))(
    Form.create()(class customerDetails extends React.Component {
        constructor(props) {
            super(props);
            this.state = {}
        }

        componentDidMount() {
            this.props.dispatch({
                type: 'customerManage/queryCustomerManageList',
                payload: {
                    status: 4,
                    businessType: Constants.NUMBER_ONE
                }
            });
        }

        handleResetFields = () => {
            if (this.editCustomer) this.editCustomer.handleResetFields();
        }

        handleCancel = (flag) => {
            if (flag) {
                this.handleResetFields();
            }
        }

        onView = (record) => {
            this.handleOpenDetail(record, false, {}, "1", true);
        }

        onAddOrder = (record) => {

            if (R.isNil(record.waiter) || R.isNil(record.manager) || R.isNil(record.tgmanager)) {
                message.error("请确认跟单经理、业务经理、通关经理是否都已经全部分配完毕！");
                return;

            }

            if (!record.extId) {
                message.error("请完成客户交接单再下单");
                return;
            }

            this.props.dispatch({
                type: 'customerManage/getCustomerById', payload: {
                    id: record.id, isApproval: false,
                    onSuccess: (customer) => {
                        this.props.dispatch({type: 'orderManage/setCustomer', payload: {customer}});//查询联系人列表

                        if (customer.isblacklist) {
                            message.error("此客户在黑名单中,如需下单请移除黑名单!");
                            return;
                        }

                        this.props.dispatch({type: 'orderManage/cleanOrder', payload: {cstid: record.id}});//清理order state 的已有订单信息
                        this.props.dispatch({type: 'orderManage/queryLinkmanList', payload: {cstId: record.id}});//查询联系人列表
                        this.refs.orderDetail.handleOpen(false, false, false, false, {}, "1", record.id);
                    }
                }
            });

        }

        handleAdd = (record) => {
            this.props.dispatch({type: 'lesseeAccount/getLesseesAccount', payload: {}});
            this.cstSettlement.handleOpen(record.id, record.customerno, record.companyname);
        }

        handleAddPt  = (record) => {
            this.lesseeSettlement.handleOpen(record.id);
        }


        onAddOutbuyProvider = (record) => {
            this.editOutbuy.handleOpen('add', null, false, record.id);
        }

        handleOpenDetail = (record, customerDisabled, searchConditions, tabActiveKey, editCustomerDisable) => {
            this.props.dispatch({
                type: 'customerManage/getCustomerById', payload: {
                    id: record.id, isApproval: false,
                    onSuccess: (customer) => {
                        let isblacklist = false;
                        if (customer.isblacklist) {
                            isblacklist = true;
                        }

                        this.props.dispatch({
                            type: 'customerManage/getLinkmanList',
                            payload: {cstId: record.id, page: this.props.customerManage.linkmanPage}
                        });//查询联系人列表
                        this.props.dispatch({
                            type: 'customerManage/getAgencyagreementList',
                            payload: {id: record.id, page: this.props.customerManage.agencyagreementPage}
                        });
                        this.props.dispatch({
                            type: 'customerManage/getRecAccList',
                            payload: {cstId: record.id, page: this.props.customerManage.recAccPage}
                        });
                        this.props.dispatch({
                            type: 'orderManage/queryOrderManageList',
                            payload: {cstId: record.id, page: this.props.orderManage.page, status: 1}
                        });
                        this.props.dispatch({
                            type: 'businessAgreement/getAgreementlList',
                            payload: {cstId: record.id, status: 1}
                        });
                        this.props.dispatch({
                            type: 'statement/getStatementsList',
                            payload: {cstId: record.id, status: 2}
                        });
                        this.props.dispatch({
                            type: 'customerManage/getListByCstIdForPage',
                            payload: {cstId: record.id, page: this.props.customerManage.marketInfoPage}
                        });

                        this.refs.customerDetail.handleOpen(customerDisabled, searchConditions, tabActiveKey, record.id, editCustomerDisable, "customerDetail");
                    }
                }
            });


        }

        handleSearch = () => {
            let values = this.props.form.getFieldsValue();
            let newPage = this.props.customerManage.page;
            newPage.page = 1;
            let time = values.time;
            this.props.dispatch({
                type: 'customerManage/queryCustomerManageList',
                payload: {
                    customerNO: values.customerNO,
                    cstName: values.cstName,
                    cstType: values.cstType,
                    cstManage: values.cstManage,
                    cstWaiter: values.cstWaiter,
                    beginTime: R.isNil(time) || R.isEmpty(time) ? null : time[0].format(dateFormat),
                    endTime: R.isNil(time) || R.isEmpty(time) ? null : time[1].format(dateFormat),
                    status: 4,
                    businessType: Constants.NUMBER_ONE,
                    page: newPage
                }
            });
        };


        columns = [
            {title: '客户编码', dataIndex: 'customerno', key: 'customerno'},

            {title: '客户名称', dataIndex: 'companyname', key: 'companyname',},

            {
                title: '客户类型', render(record) {
                    if (R.isNil(record.companytypeName) || R.isEmpty(record.companytypeName)) {
                        return "未知";
                    } else {
                        return record.companytypeName;
                    }
                }
            },

            {
                title: '业务经理', render(record) {
                    if (R.isNil(record.managerName) || R.isEmpty(record.managerName)) {
                        return "未分配";
                    } else {
                        return record.managerName;
                    }
                }
            },

            {
                title: '跟单经理', render(record) {
                    if (R.isNil(record.waiterName) || R.isEmpty(record.waiterName)) {
                        return "未分配";
                    } else {
                        return record.waiterName;
                    }
                }
            },

            {title: '创建时间', dataIndex: 'createtime', key: 'createtime'},

            {
                title: '操作', key: 'key_oprator',

                render: (text, record, index) => {

                    let addOrderButton = <RightBox resource={RightContacts.ORDER.ORDER_MANAGE_ADD} split={true}><a
                        href="#" onClick={this.onAddOrder.bind(this, record)}>添加订单</a></RightBox>;
                    let cstStatementButton = <RightBox
                        resource={RightContacts.CUSTOMER.CUSTOMER_DETAIL_STATEMENT_ADD} split={true}><a href="#" onClick={this.handleAdd.bind(this, record)}>应收款结算</a></RightBox>;
                    let ptStatementButton = <RightBox
                        resource={RightContacts.CUSTOMER.CUSTOMER_DETAIL_STATEMENT_ADD}><a href="#" onClick={this.handleAddPt.bind(this, record)}>应付款结算</a></RightBox>;

                    let addOutbuyProvider = <RightBox resource={RightContacts.ORDER.ORDER_MANAGE_ADD} split={true}><a
                        href="#" onClick={this.onAddOutbuyProvider.bind(this, record)}>添加商品供应商</a></RightBox>
                    return (
                        <span>
                            <RightBox resource={RightContacts.CUSTOMER.CUSTOMER_DETAIL_CUSTOMER_EDIT}><a href="#" onClick={this.onView.bind(this, record)}>信息维护</a>
                                <span className="ant-divider"/> </RightBox>
                            {addOutbuyProvider}
                            {addOrderButton}
                            {cstStatementButton}
                            {ptStatementButton}
                        </span>
                    );
                }
            }
        ];

        render() {
            let dataSouce = R.isNil(this.props.customerManage.dataSource) ? {} : this.props.customerManage.dataSource;
            let formItemLayout = {labelCol: {span: 6}, wrapperCol: {span: 18}};
            const {getFieldDecorator} = this.props.form;
            let values = this.props.form.getFieldsValue();
            let time = values.time;
            let pagination = {
                showTotal: total => `共 ${total} 条数据`,
                pageSize: this.props.customerManage.page.size,
                total: this.props.customerManage.page.totalRow,
                showSizeChanger: true,
                current: this.props.customerManage.page.page,
                onShowSizeChange: (current, size) => {
                    let newPage = this.props.customerManage.page;
                    newPage.size = size;
                    newPage.page = 1;
                    this.props.dispatch({
                        type: 'customerManage/queryCustomerManageList',
                        payload: {
                            customerNO: values.customerNO,
                            cstName: values.cstName,
                            cstType: values.cstType,
                            cstManage: values.cstManage,
                            cstWaiter: values.cstWaiter,
                            beginTime: R.isNil(time) || R.isEmpty(time) ? null : time[0].format(dateFormat),
                            endTime: R.isNil(time) || R.isEmpty(time) ? null : time[1].format(dateFormat),
                            status: 4,
                            businessType: Constants.NUMBER_ONE,
                            page: newPage
                        }
                    });
                },
                onChange: (pageNumber, pageSize) => {
                    let newPage = this.props.customerManage.page;
                    newPage.page = pageNumber;
                    this.props.dispatch({
                        type: 'customerManage/queryCustomerManageList',
                        payload: {
                            customerNO: values.customerNO,
                            cstName: values.cstName,
                            cstType: values.cstType,
                            cstManage: values.cstManage,
                            cstWaiter: values.cstWaiter,
                            beginTime: R.isNil(time) || R.isEmpty(time) ? null : time[0].format(dateFormat),
                            endTime: R.isNil(time) || R.isEmpty(time) ? null : time[1].format(dateFormat),
                            status: 4,
                            businessType: Constants.NUMBER_ONE,
                            page: newPage
                        }
                    });
                }
            }
            return (
                <div>

                    <Row>
                        <Col span={7}><FormItem {...formItemLayout} label={'客户代码'}>{getFieldDecorator('customerNO')(
                            <Input/>)}</FormItem></Col>
                        <Col span={7}><FormItem {...formItemLayout} label={'客户名称'}>{getFieldDecorator('cstName')(
                            <Input/>)}</FormItem></Col>
                    </Row>
                    <Row>
                        <Col span={7}><FormItem {...formItemLayout} label={'业务经理'}>{getFieldDecorator('cstManage')(
                            <Input/>)}</FormItem></Col>
                        <Col span={7}><FormItem {...formItemLayout} label={'跟单经理'}>{getFieldDecorator('cstWaiter')(
                            <Input/>)}</FormItem></Col>
                    </Row>
                    <Row>
                        <Col span={7}><FormItem {...formItemLayout} label={'客户类型'}>
                            {getFieldDecorator('cstType')(
                                <BizParams sprCode={"cstType"} style={{width: '100%'}} all={true}/>
                            )}
                        </FormItem></Col>
                        <Col span={7}>
                            <FormItem {...formItemLayout} label={'创建时间'}>
                                {getFieldDecorator('time', {})(
                                    <RangePicker
                                        style={{width: 265}}
                                        showTime={{format: 'YYYY-MM-DD'}}
                                        format="YYYY-MM-DD"
                                        placeholder={['开始时间', '结束时间']}
                                    />
                                )}
                            </FormItem>
                        </Col>
                        <Col span={7} style={{float: 'right'}}>
                            <Button type="primary" icon="search" style={{marginRight: 5}}
                                    onClick={this.handleSearch.bind(this)}>查询</Button>
                        </Col>

                    </Row>

                    <Table dataSource={this.props.customerManage.list} columns={this.columns} bordered={true}
                           size={'middle'} pagination={pagination}/>

                    <CustomerDetail ref={"customerDetail"} cstId={dataSouce.id}
                                    drawers={this.props.drawer} {...this.props.customerManage}
                                    orderManage={this.props.orderManage}
                                    businessAgreement={this.props.businessAgreement}
                                    statement={this.props.statement}
                                    dispatch={this.props.dispatch} showPA={true}
                                    capital={this.props.capital}
                                    customerReport={this.props.customerReport}
                                    blacklist={this.props.blacklist}
                                    customs={this.props.customs}
                                    handleSearch={this.handleSearch}/>

                    <CstSettlement wrappedComponentRef={(inst) => this.cstSettlement = inst} dispatch={this.props.dispatch}
                               handleSearch={this.handleSearch}/>
                    <LesseeSettlement wrappedComponentRef={(inst) => this.lesseeSettlement = inst} dispatch={this.props.dispatch}
                                      handleSearch={this.handleSearch}/>

                    <OrderDetail ref={"orderDetail"} cstId={dataSouce.id} {...this.props.orderManage}
                                 dispatch={this.props.dispatch}/>

                    <EditOutbuy wrappedComponentRef={(inst) => this.editOutbuy = inst}
                                handleSearch={this.handleSearch}/>

                </div>
            )
        }
    })
)
